package com.elinkway.infinitemovies.http.parser;

import android.util.Base64;

import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.bean.Episode;
import com.elinkway.infinitemovies.bean.PlayRecord;
import com.elinkway.infinitemovies.bean.PlaySrcBean;
import com.elinkway.infinitemovies.bean.PlaySrcList;
import com.elinkway.infinitemovies.bean.VideoDataBean;
import com.elinkway.infinitemovies.utils.SharePreferenceManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * 播放源数据
 * 对应接口 apiwebsitepaging_json.so
 */
public class VideoListParser extends LVideoMobileParser<VideoDataBean> {

    private static final String SITE = "site";
    private static final String EPISODES = "episodes";
    private static final String NOWEPISODES = "nowEpisodes";
    private static final String DOWNLOAD = "download";
    private static final String AID = "aid";
    private static final String STELOGO = "sitelogo";
    private static final String SITENAME = "sitename";
    private static final String OPENWAY = "openway";
    private static final String PLAYER = "player";
    private static final String SCRIPT = "script";
    private static final String EXTERNAL_ID = "external_id";
    private JSONArray arr;

    private static final String VIDEO_LIST = "videoList";
    private static final String ORDERLIST = "orderlist";

    private String site;
    private VideoDataBean video;
    private int currentPageInex;

    private static final String SRC = "src";
    private static final String EP_NAME = "name";
    private static final String EP_VID = "vid";
    private static final String EP_URL = "url";
    private static final String EP_PORDER = "porder";
    private static final String EP_RELEASEDATE = "releasedate";
    private static final String EP_SUBNAME = "subname";
    private static final String EP_PLS = "pls";
    private static final String EP_MID = "mid";
    private static final String VT = "vt";
    private static final String TAG_LIST = "taglist";
    private static final String ISPAY="isPay";

    public VideoListParser(String site, VideoDataBean video, int pageIndex) {
        super();
        this.site = site;
        this.video = video;
        currentPageInex = pageIndex;
    }

    @Override
    public VideoDataBean parse(JSONObject data) throws Exception {
        if (null == video) {
            video = new VideoDataBean();
        }
        if (null == data || arr.length() < 1)
            return video;
        PlaySrcList srcList = video.getSrcList();
        srcList.getPlaySrcList().clear();//清除现有的数据
        for (int i = 0; i < arr.length(); i++) {
            //解析playsrc
            JSONObject obj = arr.getJSONObject(i);
            PlaySrcBean playsrc = new PlaySrcBean();
            playsrc.setSite(obj.optString(SITE));
            playsrc.setExternalId(obj.optString(EXTERNAL_ID));
            playsrc.setEpisodeNum(obj.optString(EPISODES));
            playsrc.setNowEpisode(obj.optString(NOWEPISODES));
            playsrc.setLogo(obj.optString(STELOGO));
            playsrc.setAid(obj.optString(AID));
            playsrc.setSitename(obj.optString(SITENAME));
            playsrc.setOpenway(obj.optString(OPENWAY));
            playsrc.setIsDownload(obj.optString(DOWNLOAD));
            playsrc.setPlayer(obj.optString(PLAYER));
            playsrc.p2pDownload = obj.optInt("p2pDownload");
            if (obj.optJSONArray(SCRIPT) != null && obj.optJSONArray(SCRIPT).length() > 0) {
                playsrc.setScript(getFromBASE64(obj.optJSONArray(SCRIPT).getString(0)));
            }
            srcList.getPlaySrcList().add(playsrc);
            //解析videolist
            if (null != site && site.equals(obj.optString(SITE))) {
                video.setSrc(obj.optString(SRC));
                video.setSitename(obj.optString(SITENAME));
                video.setExternalId(obj.optString(EXTERNAL_ID));
                video.setIsDownload(obj.optString(DOWNLOAD));
                video.setOpenway(obj.optString(OPENWAY));
                if("letv".equals(site)){
                    SharePreferenceManager.saveVaule(MoviesApplication.getInstance(), SharePreferenceManager.PRIMEPLAYTYPE, obj.optString("primePlayType"));
                    SharePreferenceManager.saveVaule(MoviesApplication.getInstance(), SharePreferenceManager.FAILOVERPLAYTYPE, obj.optString("failoverPlayType"));
                    SharePreferenceManager.saveVaule(MoviesApplication.getInstance(), SharePreferenceManager.LETVDOWNLOAD, obj.optString("letvDownload"));
                }
//				video.setVt(obj.optString(VT));
                if (obj.has(ORDERLIST)) {
                    String tempList = obj.optString(ORDERLIST);
                    String[] porder = null;
                    try {
                        porder = tempList.split(";");
                        if (null != porder && porder.length > 0) {
                            ArrayList<String> porderLists = new ArrayList<String>(Arrays.asList(porder));
                            video.setmPorderLists(porderLists);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                if (obj.has(VIDEO_LIST)) {
                    JSONArray arr = obj.getJSONArray(VIDEO_LIST);
                    ArrayList<Episode> episodes = new ArrayList<>();
                    for (int j = 0; j < arr.length(); j++) {
                        Episode ep = new Episode();
                        JSONObject jsonObject = arr.getJSONObject(j);
                        ep.setSrc(obj.optString(SRC));
                        ep.setSite(site);
                        ep.setName(jsonObject.optString(EP_NAME));
                        ep.setSubName(jsonObject.optString(EP_NAME));
                        ep.setVid(jsonObject.optString(EP_VID));
                        ep.setPlay_url(jsonObject.optString(EP_URL));
                        ep.setPorder(jsonObject.optString(EP_PORDER));
                        ep.setReleaseDate(jsonObject.optString(EP_RELEASEDATE));
                        ep.setPls(jsonObject.optString(EP_PLS));
                        ep.setMid(jsonObject.optString(EP_MID));
                        ep.setGlobaVid(jsonObject.optString("globalVid"));
                        ep.setSerialid(obj.optString(AID) + jsonObject.optString(EP_PORDER));
//                        ep.setSerialid(jsonObject.optString("globalVid"));// 设置剧集下载任务标示(这种方式不可行)
                        ep.setRequest_site(PlayRecord.REQUEST_TYPE_FROM_DETAIL);
                        ep.setCloudId(jsonObject.optString("cloudId"));
                        ep.setIsdownload(jsonObject.optString("isdownload"));
                        ep.setExternalId(jsonObject.optString(EXTERNAL_ID));
                        ep.setIsPay(jsonObject.optString(ISPAY));
                        if (obj.has(EP_SUBNAME)) {
                            try {
                                String subname = jsonObject.getString(EP_SUBNAME);
                                ep.setSubName(subname);
                            } catch (JSONException e) {
                                ep.setSubName("");
                            }
                        }
                        ep.setPageIndex(currentPageInex);
                        ep.setCurrentPagePosition(j);
                        ep.setPosition((currentPageInex - 1 >= 0 ? currentPageInex - 1 : 0) * 50 + j);
                        video.getEpisodeList().add(ep);
                        episodes.add(ep);
                        playsrc.getEpisodes().add(ep);
                    }
                    video.getPageEpisodeList().put(String.valueOf(currentPageInex - 1), episodes);
                    video.setPlaySrcBean(playsrc);
                    video.setSubsrc(obj.optString("subsrc"));
                }
                if (obj.has(TAG_LIST)) {
                    JSONArray arr = obj.optJSONArray(TAG_LIST);
                    ArrayList<String> arrayList = new ArrayList<>();
                    for(int j = 0; j < arr.length(); j++) {
                        if (arr.get(j) != null) {
                            arrayList.add(arr.get(j).toString());
                        }
                    }
                    video.setEpisodePageList(arrayList);
                }
            }
        }
        video.setSrcList(srcList);
        return video;

    }

    @Override
    protected JSONObject getData(String data) throws JSONException {
        // TODO Auto-generated method stub
        arr = new JSONArray(data);
        data = "{\"data\":\"data\"}";
        return super.getData(data);
    }

    // 将 BASE64 编码的字符串 s 进行解码
    public static String getFromBASE64(String s) {
        if (s == null) return null;
        try {
            byte[] b = Base64.decode(s.getBytes(),Base64.DEFAULT);
            return new String(b);
        } catch (Exception e) {
            return null;
        }
    }
}
